﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace XFFSM
{

    public enum ConditionState
    {
        // 满足
        Meet,
        // 未满足
        NotMeet

    }

    public class FSMCondition 
    {

        #region 字段
        private FSMConditionData data;

        private FSMParameterData parameter;

        public Action onConditionMeet;

        private static Dictionary<CompareType, IPamaterCompare> Compares = new Dictionary<CompareType, IPamaterCompare>();

        #endregion

        #region 属性
        public ConditionState state { get; private set; } = ConditionState.NotMeet;

        private IPamaterCompare compare => GetCompare(data.compareType);

        public FSMParameterData Parameter => parameter;

        #endregion

        static FSMCondition() {
            InitCompares();
        }

        public FSMCondition(FSMConditionData data, RuntimeFSMControllerInstance controller) {
            this.data = data;

            if (controller.parameters.ContainsKey(data.parameterName)) {
                parameter = controller.parameters[this.data.parameterName];
            }

            if (parameter != null) 
                parameter.onValueChange += CheckParameterValueChange;
            

            // 检测条件
            CheckParameterValueChange();

        }

        public void CheckParameterValueChange() {

            // 判断条件有没有满足
            if (compare.IsMeetCondition(this.parameter, data.targetValue))
            {
                state = ConditionState.Meet;
                onConditionMeet?.Invoke();
            }
            else {
                state = ConditionState.NotMeet;
            } 
        }

        private static void InitCompares() {
            if (Compares.Count == 0) {
                Compares.Add(CompareType.Equal, new EqualCompare());
                Compares.Add(CompareType.Greater, new GreaterCompare());
                Compares.Add(CompareType.Less, new LessCompare());
                Compares.Add(CompareType.NotEqual, new NotEqualCompare());
            }
        }

        public static IPamaterCompare GetCompare(CompareType type) {
            IPamaterCompare pamaterCompare;
            if ( Compares.TryGetValue(type,out pamaterCompare) ) {
                return pamaterCompare;
            }
            return null;
        }

    }

}
